#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import click
import asyncio
from rich.console import Console
from rich.progress import Progress
from .core.parser import Parser
from .core.config import Config
from .core.logger import Logger
from .utils.downloader import Downloader
from .utils.merger import Merger
from .core.models import VideoQuality

console = Console()

def update_progress(progress, task, downloaded, total):
    """更新进度条"""
    if total > 0:
        percentage = int(downloaded * 100 / total)
        progress.update(task, completed=percentage)

def get_quality_height(quality_str: str) -> int:
    """从质量字符串中提取高度值"""
    if not quality_str:
        return 0
    # 移除 'p' 或 'P' 后缀
    height_str = quality_str.lower().rstrip('p')
    try:
        return int(height_str)
    except ValueError:
        return 0

def select_quality(qualities, target_quality: str) -> VideoQuality:
    """选择指定质量的视频流"""
    if not target_quality:
        # 如果没有指定质量，返回最高质量
        return qualities[0]
    
    target_height = get_quality_height(target_quality)
    if target_height == 0:
        return qualities[0]
    
    # 找到最接近目标质量的视频流
    closest_quality = min(qualities, key=lambda q: abs(q.height - target_height))
    return closest_quality

@click.command()
@click.argument('url')
@click.option('-q', '--quality', help='视频质量（如：1080p, 720p, 480p 等）')
@click.option('-f', '--format', help='输出格式（如：mp4, flv 等）')
@click.option('-d', '--danmaku', is_flag=True, help='下载弹幕')
@click.option('-s', '--subtitle', is_flag=True, help='下载字幕')
@click.option('--cookie', help='设置cookie')
def main(url, quality, format, danmaku, subtitle, cookie):
    """BBDown - B站视频下载工具"""
    try:
        # 初始化配置
        config = Config()
        if cookie:
            config.set_cookie(cookie)
        
        # 初始化日志
        logger = Logger()
        
        # 创建事件循环
        loop = asyncio.get_event_loop()
        
        # 解析视频信息
        parser = Parser(url, config)
        video_info = loop.run_until_complete(parser.parse())
        
        # 创建下载器和合并器
        downloader = Downloader()
        merger = Merger()
        
        # 创建输出目录
        output_dir = os.path.join(os.getcwd(), video_info.title)
        os.makedirs(output_dir, exist_ok=True)
        
        with Progress() as progress:
            # 下载视频和音频
            for part in video_info.parts:
                # 获取视频和音频URL
                video_url, audio_url, qualities = loop.run_until_complete(parser.get_video_play_info(video_info.bvid, part.cid))
                
                # 选择指定质量的视频流
                selected_quality = select_quality(qualities, quality)
                video_url = selected_quality.url
                
                # 设置输出路径
                output_format = format or 'mp4'  # 默认使用 mp4 格式
                video_path = os.path.join(output_dir, f"{part.title}_video.{output_format}")
                audio_path = os.path.join(output_dir, f"{part.title}_audio.m4a")
                output_path = os.path.join(output_dir, f"{part.title}.{output_format}")
                
                # 创建下载任务
                video_task = progress.add_task(f"[cyan]下载视频: {part.title} ({selected_quality.height}P)", total=100)
                audio_task = progress.add_task(f"[cyan]下载音频: {part.title}", total=100)
                
                # 下载视频
                loop.run_until_complete(
                    downloader.download_video(
                        video_url,
                        video_path,
                        lambda d, t: update_progress(progress, video_task, d, t)
                    )
                )
                
                # 下载音频
                loop.run_until_complete(
                    downloader.download_video(
                        audio_url,
                        audio_path,
                        lambda d, t: update_progress(progress, audio_task, d, t)
                    )
                )
                
                # 合并视频和音频
                merger.merge_video_audio(video_path, audio_path, output_path)
                
                # 删除临时文件
                os.remove(video_path)
                os.remove(audio_path)
                
                # 下载弹幕
                if danmaku:
                    danmaku_task = progress.add_task(f"[cyan]下载弹幕: {part.title}", total=100)
                    danmaku_path = os.path.join(output_dir, f"{part.title}.xml")
                    loop.run_until_complete(
                        downloader.download_danmaku(
                            part.danmaku_url,
                            danmaku_path
                        )
                    )
                
                # 下载字幕
                if subtitle and part.subtitles:
                    for sub in part.subtitles:
                        subtitle_task = progress.add_task(f"[cyan]下载字幕: {part.title} - {sub.language}", total=100)
                        subtitle_path = os.path.join(output_dir, f"{part.title}_{sub.language}.srt")
                        loop.run_until_complete(
                            downloader.download_subtitle(
                                sub.url,
                                subtitle_path
                            )
                        )
        
        console.print("[green]下载完成！")
        
    except Exception as e:
        console.print(f"[red]错误: {str(e)}")
        raise click.Abort()

if __name__ == '__main__':
    main() 